/*
 * @lc app=leetcode.cn id=1893 lang=typescript
 *
 * [1893] 检查是否区域内所有整数都被覆盖
 */

// @lc code=start
function isCovered(ranges: number[][], left: number, right: number): boolean {
  ranges.sort((a: number[], b: number[]): number => {
    if (a[0] === b[0]) return a[1] - b[1];
    else return a[0] - b[0];
  });

  const mergeRanges: number[][] = [];
  let l: number;
  let r: number;
  // 合并重复区间
  for (let i = 0; i < ranges.length; i++) {
    if (i === 0) {
      l = ranges[i][0];
      r = ranges[i][1];
    }

    if (r + 1 >= ranges[i][0]) {
      r = Math.max(r, ranges[i][1]);
    } else {
      mergeRanges.push([l, r]);
      l = ranges[i][0];
      r = ranges[i][1];
    }

    if (i === ranges.length - 1) {
      mergeRanges.push([l, r]);
    }
  }
  // 判断是否在区间内
  for (const range of mergeRanges) {
    const [l, r] = range;
    if (left >= l && right <= r) return true;
  }

  return false;
}
// @lc code=end
